package org.mii.safeguard_v1.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.Preferences;
import org.extremecomponents.table.core.PreferencesConstants;
import org.extremecomponents.table.core.TableConstants;
import org.extremecomponents.table.core.TableModelUtils;
import org.extremecomponents.table.core.TableProperties;
import org.extremecomponents.table.limit.Limit;
import org.extremecomponents.table.limit.LimitFactory;
import org.extremecomponents.table.limit.TableLimit;
import org.extremecomponents.table.limit.TableLimitFactory;

/**
 * extremeTable的分页工具类
 * 
 * @author quanxiwei
 * 
 */
public class EcTablePageUtil {
	public final static String TABLE_ID = "ec";
	
	/**
	 * 获得ectable分页的limit属性 该属性包含了分页的基本信息，例如：每页显示条数，当前页
	 * @param request：HttpServletRequest
	 * @param tableId:ecTable 的ID，如果用的是默认的tableID，可以传递该值为null
	 * @return org.extremecomponents.table.limit.Limit
	 * @author QUANXIWEI
	 */
	static public Limit getLimit(HttpServletRequest request, String tableId) {
		Context context = new HttpServletRequestContext(request);

		if (StringUtils.isBlank(tableId)) {
			tableId = TABLE_ID;
		}

		// 这段取得分页每页的大小 pagesize<---->defaultRowsDisplayed
		Preferences preferences = new TableProperties();
		preferences.init(null, TableModelUtils.getPreferencesLocation(context));

		// 注意：此处取值时，如果后台配置文件里有配置，就从里面取，反之取15
		int defaultRowsDisplayed = Integer.parseInt(preferences
				.getPreference(PreferencesConstants.TABLE_ROWS_DISPLAYED));

		String crdStr = tableId + "_" + TableConstants.CURRENT_ROWS_DISPLAYED;
		if (request.getParameter(crdStr) != null) {
			defaultRowsDisplayed = Integer.parseInt(request
					.getParameter(crdStr));
		}

		LimitFactory limitFactory = new TableLimitFactory(context, tableId);
		TableLimit limit = new TableLimit(limitFactory);
		limit.setRowAttributes(Integer.MAX_VALUE, defaultRowsDisplayed);
		return limit;
	}
}
